import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElButton,
  ElSpace,
  ElLink,
  ElMessage,
  ElMessageBox
} from 'element-plus'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AddStrategy from './addStrategy'
import styles from '../../index.module.scss'
import SendDevs from './sendDevs'
import TaskDetail from './taskDetail'

// 单灯策略管理
export default defineComponent(function SingleLampStrategy() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})

  const state = reactive({
    exportVisible: false,
    visible: false,
    addVisible: false,
    type: 'add',
    record: {},
    sendVisible: false,
    status: 1, // 下发状态   0待发送，1下发成功 2失败
    detailVisible: false
  })
  const userState = useVuexGetters('user', ['permission'])
  const taskDetailRef = ref()
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '策略名称',
      prop: 'taskName',
      minWidth: 140,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '策略信息',
      prop: 'info',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      disabled: true,
      render: ({ row }) => (
        <>
          <div style="color:red">
            {row.startDate} ~ {row.endDate}
          </div>
          {row.info?.split('|')?.map((item) => (
            <div>{item}</div>
          ))}
        </>
      )
    },
    {
      label: '管理分组',
      prop: 'groupNames',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '下发成功数',
      prop: 'successNum',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => getDevs(row, 1)}>
            {row.successNum}
          </ElLink>
        </ElSpace>
      )
    },
    {
      label: '下发失败数',
      prop: 'failNum',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => getDevs(row, 2)}>
            {row.failNum}
          </ElLink>
        </ElSpace>
      )
    },
    {
      label: '待下发',
      prop: 'waitNum',
      minWidth: 180,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => getDevs(row, 0)}>
            {row.waitNum}
          </ElLink>
        </ElSpace>
      )
    },
    // {
    //   label: '创建人',
    //   prop: 'createUser',
    //   minWidth: 160,
    //   align: 'center',
    //   showOverflowTooltip: true,
    //   sortable: true
    // },
    // {
    //   label: '更新时间',
    //   prop: 'updateTime',
    //   minWidth: 160,
    //   align: 'center',
    //   showOverflowTooltip: true,
    //   sortable: true
    // },
    {
      label: '更新人',
      prop: 'updateUserName',
      minWidth: 160,
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 200,
      align: 'center',
      fixed: 'right',
      // unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => openDetail(row.id)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情
          </ElLink>
          {userState.permission.value.has('lamp_lampTask_update') && (
            <ElLink type="primary" onClick={() => handleChangeAddsingleLampModal('update', row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('lamp_lampTask_remove') && (
            <ElLink type="primary" onClick={() => handleDeleteTask(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  // 任务下发设备
  const getDevs = (row: FormValuesType, status: number) => {
    state.sendVisible = !state.sendVisible
    state.record = row || {}
    state.status = status
  }
  const sendModalClose = () => {
    state.sendVisible = false
  }
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  // 打开新增/编辑策略弹窗
  const handleChangeAddsingleLampModal = (type: string, record?: FormValuesType) => {
    state.type = type
    state.record = record || {}
    state.addVisible = !state.addVisible
    if (!state.addVisible) handleChangeValueActionSearchList()
  }

  // 删除
  const handleDeleteTask = (record: FormValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {<p class="delete-title">确认删除数据？</p>}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('singleLamp/TaskDelete', { ids: params }).then(async (result) => {
          if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          proSaasTableRef.value!?.toSearch()
        })
      })
      .catch(() => {})
  }
  // 详情
  const openDetail = (id?: string) => {
    taskDetailRef.value.open(id)
  }
  onMounted(() => {})
  return () => (
    <ElCard>
      {
        <ProSaasTable<FormValuesType>
          tableId="monitor_singleLampStrategy_index"
          ref={proSaasTableRef}
          columns={columns}
          searchParams={formValues}
          hasSelection
          dispatchType="singleLamp/TaskList"
          searchFormProps={{
            model: formValues
          }}
          headerTitle={
            <>
              {userState.permission.value.has('lamp_lampTask_add') && (
                <ElButton type="primary" onClick={() => handleChangeAddsingleLampModal('add')}>
                  <AliIcon type="icon-xinzeng" />
                  &nbsp; 新增
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="taskName" prop="taskName" label="">
              <ElInput
                v-model={formValues.taskName}
                placeholder="策略名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>
          ]}
        />
      }
      {state.addVisible && (
        <AddStrategy
          visible={state.addVisible}
          cancel={handleChangeAddsingleLampModal}
          type={state.type}
          record={state.record}
          onSubmitForm={handleChangeValueActionSearchList}
        />
      )}
      {state.sendVisible && (
        <SendDevs cancel={sendModalClose} detail={state.record} status={state.status} />
      )}
      <TaskDetail ref={taskDetailRef} />
    </ElCard>
  )
})
